package com.weyoung.app.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weyoung.app.common.convention.exception.ClientException;
import com.weyoung.app.mapper.EmergencyContactsMapper;
import com.weyoung.app.pojo.dto.req.EmergencyContactAddReqDTO;
import com.weyoung.app.pojo.dto.resp.EmergencyContactRespDTO;
import com.weyoung.app.pojo.entity.EmergencyContacts;
import com.weyoung.app.service.EmergencyContactsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 紧急联系人 Service 实现类
 */
@Service
@RequiredArgsConstructor
public class EmergencyContactsServiceImpl extends ServiceImpl<EmergencyContactsMapper, EmergencyContacts> implements EmergencyContactsService {

    private final EmergencyContactsMapper emergencyContactsMapper;
    @Override
    public Void addEmergencyContact(EmergencyContactAddReqDTO requestParam) {
        String openID = StpUtil.getLoginId().toString();
        if (StrUtil.isBlank(openID)) {
            throw new ClientException("用户未登录");
        }
        if (StrUtil.isBlank(requestParam.getName()) || StrUtil.isBlank(requestParam.getPhone())) {
            throw new ClientException("姓名或手机号不能为空");
        }
        if (!requestParam.getPhone().matches("^1[3456789]\\d{9}$")) {
            throw new ClientException("手机号格式不正确");
        }
        baseMapper.insert(EmergencyContacts.builder()
                .openid(openID)
                .contactName(requestParam.getName())
                .contactPhone(requestParam.getPhone())
                .build());
        return null;
    }

    @Override
    public List<EmergencyContactRespDTO> getList() {
        String openID = StpUtil.getLoginId().toString();
        if (StrUtil.isBlank(openID)) {
            throw new ClientException("用户未登录");
        }
       List<EmergencyContactRespDTO> list = emergencyContactsMapper.getList(openID);
        return list;
    }

    @Override
    public List<EmergencyContactRespDTO> deleteById(Integer id) {
        if (id == null) {
            throw new ClientException("id不能为空");
        }
        String openID = StpUtil.getLoginId().toString();
        if (StrUtil.isBlank(openID)) {
            throw new ClientException("用户未登录");
        }
        //根据id删除
        baseMapper.delete(Wrappers.lambdaQuery(EmergencyContacts.class)
                .eq(EmergencyContacts::getContactId, id));

        return emergencyContactsMapper.getList(openID);
    }

}